# -*- coding: utf-8 -*-
# @Author  : Pony.guan
# @Time    : 2021/11/8 下午4:46
# Description:

import decimal
import datetime

import simplejson
import numpy
from tornado.web import RequestHandler

from config import Debug


class MyEncoder(simplejson.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, numpy.integer):
            return int(obj)
        elif isinstance(obj, numpy.floating):
            return float(obj)
        elif isinstance(obj, numpy.ndarray):
            return obj.tolist()
        elif isinstance(obj, decimal.Decimal):
            return float(obj)
        elif isinstance(obj, datetime.datetime):
            return obj.strftime('%Y%m%d %X.%f')
        elif isinstance(obj, datetime.date):
            return obj.strftime('%Y%m%d')
        else:
            return super(MyEncoder, self).default(obj)


class BaseHandler(RequestHandler):
    def json_response(self, data):
        self.set_header('Content-Type', 'application/json; charset=utf-8')
        self.write(simplejson.dumps(data, cls=MyEncoder, ignore_nan=True, ensure_ascii=False))
        self.finish()

    def set_default_headers(self):
        if Debug:
            self.set_header("Access-Control-Allow-Origin", "*")
            self.set_header("Access-Control-Allow-Headers", "x-requested-with")
            self.set_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE, PATCH')
